package com.ics.cmsadmin.frame.profit.role;

import com.ics.cmsadmin.frame.profit.ProfitInfo;
import com.ics.cmsadmin.frame.profit.bean.GradientRateData;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import static com.ics.cmsadmin.frame.profit.ProfitTypeEnum.GRADIENT_RATE;

/**
 * Created by Administrator on 2017/4/19.
 */
public class GradientRateRole implements ProfitRole {

    // 分润利率
    private List<BigDecimal> rates;
    // 分润界限
    private List<BigDecimal> limits;

    public GradientRateRole(List<BigDecimal> rates, List<BigDecimal> limits) {
        if (CollectionUtils.isEmpty(rates) || limits == null || rates.size() != limits.size() + 1){
            throw new RuntimeException("参数有误,参数不能为空,或rates的个数要比limits多一个");
        }
        this.rates = rates;
        this.limits = limits;
    }

    @Override
    public ProfitInfo getProfitInfo(BigDecimal orderMoney, long studentNum) {
        BigDecimal rate = findRate(studentNum);
        BigDecimal shareMoney = orderMoney.multiply(rate)
            .divide(new BigDecimal(100),2, BigDecimal.ROUND_DOWN);
        return ProfitInfo.builder()
            .profitTypeEnum(GRADIENT_RATE)
            .orderMoney(orderMoney)
            .student(studentNum)
            .shareRate(rate)
            .shareMonery(shareMoney)
            .build();
    }

    // 查看学生数在那个区间
    private BigDecimal findRate(long studentNum) {
        int result = 0;
        BigDecimal student = new BigDecimal(studentNum);
        for(BigDecimal limit : limits){
            if (student.compareTo(limit) < 0){
                return rates.get(result);
            }
            result ++;
        }
        return rates.get(result);
    }

    @Override
    public Object getData() {
        List<GradientRateData> result = new ArrayList<>();
        if (CollectionUtils.isEmpty(this.rates)) {
            return result;
        }
        for (int i = 0; i < this.rates.size(); i++){
            result.add(GradientRateData.builder()
                .minStudent(i == 0 ? "0" : this.limits.get(i - 1).toString())
                .maxStudent(i == this.rates.size() - 1 ? "无穷大" : this.limits.get(i).toString())
                .rate(this.rates.get(i).toString())
                .build());
        }
        return result;
    }
}
